package com.lagou.rpc.consumer.postProcessor;

import com.lagou.rpc.consumer.anno.RpcAutowired;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;

@Component
public class RpcBeanPostProcessor implements BeanPostProcessor {
    @Value("${rpc.servers.port}")
    public int[] mapList;

    @PostConstruct
    public void init(){
        RpcClientProxy.mapList = mapList;
    }

    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(RpcAutowired.class)) {
                field.setAccessible(true);
                if (field.get(bean) == null)
                    field.set(bean, RpcClientProxy.createProxy(field.getType()));
            }
        }
        return bean;
    }
}
